<?php

/**
 * @content: 接收上传过来的体征数据
 * @Author:  Groube
 * @Date:    2017-03-06 17:00:00
 * @version  $Id$
 */
class TizhengDataUploadController extends Yaf_Controller_Abstract {

    /**
     * @Title  禁用模板功能
     * @Author Groube
     * @Param  /
     * @Return /
     * @Date 2017/03/08 14:30
     */
    public function init() {
        $yiyuan_id = isset($_REQUEST['yiyuan_id']) ? $_REQUEST['yiyuan_id'] : "";

        if($yiyuan_id === "" ){
            Utility::apiJsonError(20028, '请输入医院ID');
        }elseif(!ctype_digit("$yiyuan_id")){
            Utility::apiJsonError(20027, '医院ID必须是整型');
        }

        Yaf_Dispatcher::getInstance()->disableView();
    }


    /**
     * @Title  入口方法
     * @Author Groube
     * @Param  /
     * @Return /
     * @Date 2017/03/08 14:20
     */
    function indexAction(){
        $request = $this->getRequest();
        $data = $request->getPost('data','');
        $user_department_id = $request->getPost('user_department_id','');
        $str_yiyuan_id = $request->getPost('yiyuan_id',0);
        $yiyuan_id = (int)$str_yiyuan_id;

//         if(Yaconf::get("config$yiyuan_id.fenbiao_state") == 'true'){
//             //分表机制开启
//             $zhuyuan_tizheng = "zhuyuan_tizheng_".$user_department_id;
//         }else{
//             $zhuyuan_tizheng = "zhuyuan_tizheng";
//         }
        $zhuyuan_tizheng = "zhuyuan_tizheng";
        /*是否开启压缩 默认开启*/
        $compression_http_data = $request->getPost('compression_http_data','off');

        //解压缩数据
        $upload_data = json_decode(Utility::uncompress($data,$compression_http_data),true);

        if(empty($upload_data)){
            Utility::apiJsonError(40011,'(Method:接收上传过来的体征数据)数据不能为空!');
        }

        $exist_batch = array();
        $batch_operation_result = array();
        $index = 0;
        foreach($upload_data as $one){
            $zhuyuan_id = isset($one['zhuyuan_id']) ? trim($one['zhuyuan_id']) : '';
            $biaodan_type = isset($one['biaodan_type']) ? trim($one['biaodan_type']) : '';
            $jiancha_type = isset($one['jiancha_type']) ? trim($one['jiancha_type']) : '';
            $jiancha_fangshi = isset($one['jiancha_fangshi']) ? trim($one['jiancha_fangshi']) : '';
            $jiancha_shijian_duan = isset($one['jiancha_shijian_duan']) ? trim($one['jiancha_shijian_duan']) : '';
            $jiancha_time = isset($one['jiancha_time']) ? trim($one['jiancha_time']) : '';
            $patient_id = isset($one['patient_id']) ? trim($one['patient_id']) : '';
            $jiancha_doctor_name = isset($one['jiancha_doctor_name']) ? trim($one['jiancha_doctor_name']) : '';
            $jiancha_doctor_id = isset($one['jiancha_doctor_id']) ? trim($one['jiancha_doctor_id']) : '';
            $jiancha_danwei = isset($one['jiancha_danwei']) ? trim($one['jiancha_danwei']) : '';
            $jiancha_value = isset($one['jiancha_value']) ? trim($one['jiancha_value']) : '';
            $beizhu = isset($one['beizhu']) ? trim($one['beizhu']) : '';
            $batch_id = isset($one['batch_id']) ? trim($one['batch_id']) : '';
            $input_type = isset($one['input_type']) ? trim($one['input_type']) : '';
            $data_source = isset($one['data_source']) ? trim($one['data_source']) : '';
            $batch_result = isset($one['batch_result']) ? trim($one['batch_result']) : '';

            if($jiancha_shijian_duan){
                $zhuyuan_tizheng_info = array('zhuyuan_id' => $zhuyuan_id,'biaodan_type' => $biaodan_type,'jiancha_type' => $jiancha_type,'jiancha_fangshi' => $jiancha_fangshi,'jiancha_shijian_duan' => $jiancha_shijian_duan,'jiancha_time' => $jiancha_time,'yiyuan_id' => $yiyuan_id);
            }else{
                $zhuyuan_tizheng_info = array('zhuyuan_id' => $zhuyuan_id,'biaodan_type' => $biaodan_type,'jiancha_type' => $jiancha_type,'jiancha_fangshi' => $jiancha_fangshi,'jiancha_time' => $jiancha_time,'yiyuan_id' => $yiyuan_id);
            }

            $batch_operation_result[$index]['batch_update_zhuyuan_tizheng'] = $zhuyuan_tizheng_info;

            $batch_operation_result[$index]['batch_insert_zhuyuan_tizheng'] = array(
                'patient_id' => $patient_id,
                'zhuyuan_id' => $zhuyuan_id,
                'jiancha_time' => $jiancha_time,
                'jiancha_doctor_name' => $jiancha_doctor_name,
                'jiancha_doctor_id' => $jiancha_doctor_id,
                'jiancha_type' => $jiancha_type,
                'jiancha_danwei' => $jiancha_danwei,
                'jiancha_value' => $jiancha_value,
                'jiancha_fangshi' => $jiancha_fangshi,
                'beizhu' => $beizhu,
                'modify_time' => date('Y-m-d H:i:s',time()),
                'jiancha_shijian_duan' => $jiancha_shijian_duan,
                'batch_id' => $batch_id,
                'input_type' => $input_type,
                'data_source' => $data_source,
                'biaodan_type' => $biaodan_type,
                'yiyuan_id' => $yiyuan_id
            );

            if(!isset($exist_batch[$batch_id]) && !empty($batch_id)){
                $batch_operation_result[$index]['batch_insert_zhuyuan_tizheng_batch'] = array(
                    'batch_id' => $batch_id,
                    'create_hushi_id' => $jiancha_doctor_id,
                    'create_hushi_name' => $jiancha_doctor_name,
                    'create_time' => $jiancha_time,
                    'batch_result' => $batch_result,
                    'yiyuan_id' => $yiyuan_id
                );

                $exist_batch[$batch_id] = $batch_id;
            }

            $index++;
        }

        $status = $this->batch_operation($batch_operation_result);
        $statr = array('state' => $status);
        $statr['error'] = $status =='ok' ? "200" : 'error';
        $statr['msg'] = "";
        $async_result_json = json_encode($statr);

        // 压缩数据
        $async_result_json = Utility::compress($async_result_json,$compression_http_data);
        echo $async_result_json;
    }


    /**
     * @Title  批量操作
     * @Author Groube
     * @Param  array  $batch_operation_result
     * @Return string $status
     * @Date 2017/03/08 15:00
     */
     public function batch_operation($batch_operation_result){
         $db = Kohana_Database::instance();
         $db->begin();
         $status = 'ok';
         try{
             $this->batch_detail($batch_operation_result);
             $db->commit();
         }catch (Database_Expression $e){
         	throw new DatabaseExpression();
             $db->rollback();
             $status = 'error';
         }

         return $status;
    }


    /**
     * @Title  批量操作(执行语句)
     * @Author Groube
     * @Param  array  $batch_operation_result
     * @Return /
     * @Date 2017/03/08 15:10
     */
    public function batch_detail($batch_operation_result){
		$array_count = count($batch_operation_result);
        foreach($batch_operation_result as $key => $value){
            foreach($value as $kk => $vv){

                if($kk == 'batch_update_zhuyuan_tizheng'){
                    $sql = 'UPDATE zhuyuan_tizheng SET state = 0 WHERE zhuyuan_id = :zhuyuan_id AND biaodan_type = :biaodan_type AND jiancha_type = :jiancha_type AND jiancha_fangshi = :jiancha_fangshi AND yiyuan_id = :yiyuan_id';
                    if(isset($vv['jiancha_shijian_duan'])){
                        $sql .= ' AND jiancha_shijian_duan = :jiancha_shijian_duan AND DATE(jiancha_time) = :jiancha_time';
                    }else{
                        $sql .= ' AND jiancha_time = :jiancha_time';
                    }

                    $buzt_query = DB::query(Database::UPDATE,$sql);
                    $buzt_query->param(':zhuyuan_id',$vv['zhuyuan_id']);
                    $buzt_query->param(':biaodan_type',$vv['biaodan_type']);
                    $buzt_query->param(':jiancha_type',$vv['jiancha_type']);
                    $buzt_query->param(':jiancha_fangshi',$vv['jiancha_fangshi']);
                    $buzt_query->param(':yiyuan_id',$vv['yiyuan_id']);

                    if(isset($vv['jiancha_shijian_duan'])){
                        $buzt_query->param(':jiancha_shijian_duan',$vv['jiancha_shijian_duan']);
                        $buzt_query->param(':jiancha_time',date("Y-m-d",strtotime(trim($vv['jiancha_time']))));
                    }else{
                    	$buzt_query->param(':jiancha_time',date("Y-m-d",$vv['jiancha_time']));
                    }


                    //echo $buzt_query;echo ";";
                    $buzt_query->execute();
                }

                // if($kk == 'batch_insert_zhuyuan_tizheng'){
                // 	$buzfl_query = DB::insert('zhuyuan_tizheng')->columns(array_keys($vv))->values(array_values($vv));
                // 	//echo $buzfl_query;echo ";";
                // 	$buzfl_query ->execute();
                // }
                // add weizd @20170630 批量入库
                if($kk == 'batch_insert_zhuyuan_tizheng'){
                    $list[$key] = array_values($vv);
                    if($key == $array_count-1  ){
                        $buzfl_query = DB::insert('zhuyuan_tizheng')->columns(array_keys($vv))->values(array_values($list));
                        $buzfl_query_1=  str_replace("((","(",$buzfl_query);
                        $buzfl_query_3=  str_replace("))",")",$buzfl_query_1);
                        // echo $buzfl_query_3;echo ";";
                        $insert_sql = DB::query(Database::INSERT, $buzfl_query_3)->execute();
                    }


                }

                if($kk == 'batch_insert_zhuyuan_tizheng_batch'){
                    $batch_id = $vv['batch_id'];
                    DB::delete('zhuyuan_tizheng_batch')
                        ->where('batch_id', '=', $batch_id)
                        ->execute();
                	$buzfl_query = DB::insert('zhuyuan_tizheng_batch')->columns(array_keys($vv))->values(array_values($vv));
                	//echo $buzfl_query;echo ";";
                	$buzfl_query->execute();
                }
            }
        }
    }


    /**
     * 计算指定日期到当前日期的天数
     * @param  [type] $date [description]
     * @return [type]       [description]
     */
    function zpd_date_diff($date){
        /*计算天数*/
        $datetime1 = date_create(substr($date, 0, 10));
        $datetime2 = date_create(date('Y-m-d'));
        $interval  = date_diff($datetime1, $datetime2);
        return $interval->format('%a');
    }


    /**
     * 获取手术时间
     * @param  [type] $zhuyuan_id [description]
     */
    public function get_shoushu_date($zhuyuan_id,$yiyuan_id){
        $result = DB::select('jiancha_time')->from('zhuyuan_tizheng')
            ->where('zhuyuan_id','=',$zhuyuan_id)
            ->where('jiancha_type','=','操作')
            ->where('jiancha_fangshi','=','手术')
            ->where('yiyuan_id','=',$yiyuan_id)
            ->execute()
            ->as_array();

        if(!empty($result)){
            $date = $result[0]['jiancha_time'];
        }else{
            $date = '';
        }

        return $date;
    }


    /**
     * 获取是否发热以及发热的级别
     * @param  [type] $zhuyuan_id      [住院号]
     * @param  [type] $temperature     [当次测量体温值]
     * @param  [type] $zhuyuan_tizheng [体温数据表名称]
     */
    public function get_fare_level($zhuyuan_id,$temperature,$zhuyuan_tizheng,$yiyuan_id){
        $fare_level = 0;
        $is_fare = 1;
        if((float)$temperature >= 37 && (float)$temperature < 37.5){
            $fare_level = 1;
        }elseif((float)$temperature >= 37.5 && (float)$temperature < 38.5){
            $fare_level = 2;
        }elseif((float)$temperature >= 38.5){
            $fare_level = 3;
        }else{
            $high = $this->get_tiwen_for_72($zhuyuan_id,$zhuyuan_tizheng,$yiyuan_id);
            if(isset($high['jiancha_value']) && (float)$high['jiancha_value'] < 37){
                //发热转非发热
                $is_fare = 0;
            }else{
                //发热恢复中患者同发热一级患者测量计划一样
                $is_fare = 1;
                $fare_level = 1;
            }
        }

        return [$is_fare,$fare_level];
    }


    /**
     * 获取病人近72小时内的最高体温的记录
     * @param  [type] $zhuyuan_id      [description]
     * @param  [type] $zhuyuan_tizheng [description]
     * @return [type]                  [description]
     */
    public function get_tiwen_for_72($zhuyuan_id,$zhuyuan_tizheng,$yiyuan_id){
        $sql = 'SELECT * FROM '.$zhuyuan_tizheng.' WHERE zhuyuan_id = :zhuyuan_id AND jiancha_type = \'体温\' AND jiancha_fangshi = \'腋温\' AND yiyuan_id = :yiyuan_id';
        $interval = array("value"=>"3", "unit"=>"MINUTE");
        $sql .= ' AND '.Utility::getIntervalSqlString("jiancha_time",$interval);
        $query = DB::query(Database::SELECT, $sql);
        $query->param(':zhuyuan_id',$zhuyuan_id);
        $query->param(':yiyuan_id',$yiyuan_id);
        $zhuyuan_tizheng_info = $query->execute()->as_array();
        if(!empty($zhuyuan_tizheng_info)){
            $high_shuju = $zhuyuan_tizheng_info[0];
        }else{
            $high_shuju = '';
        }

        return $high_shuju;
    }


    /**
     * 获取测量时间字符串
     * @param  [type] $patient_level [description]
     * @param  [type] $fare_level    [description]
     * @param  [type] $is_fara       [description]
     */
    public function get_celiang_time_string($patient_level, $fare_level, $is_fara){
        switch ($patient_level){
            case 1:  //正常
                if($is_fara == 1){
                    switch($fare_level){
                        case 1:
                            $ret = [3,'06:00,14:00,18:00'];
                            break;
                        case 2:
                            $ret = [4,'06:00,14:00,18:00,22:00'];
                            break;
                        case 3:
                            $ret = [6,'02:00,06:00,10:00,14:00,18:00,22:00'];
                            break;
                        default:
                            $ret = [];
                            break;
                    }
                }else{
                    $ret = [1,'14:00'];
                }
                break;
            case 2:  //新入院3天内的
                if($is_fara == 1){
                    switch($fare_level){
                        case 1:
                            $ret = [3,'06:00,14:00,18:00'];
                            break;
                        case 2:
                            $ret = [4,'06:00,14:00,18:00,22:00'];
                            break;
                        case 3:
                            $ret = [6,'02:00,06:00,10:00,14:00,18:00,22:00'];
                            break;
                        default:
                            $ret = [];
                            break;
                    }
                }else{
                    $ret = [2,'06:00,14:00'];
                }
                break;
            case 3:  //手术后三天的
                if($is_fara == 1){
                    switch($fare_level){
                        case 1:
                            $ret = [3,'06:00,14:00,18:00'];
                            break;
                        case 2:
                            $ret = [4,'06:00,14:00,18:00,22:00'];
                            break;
                        case 3:
                            $ret = [6,'02:00,06:00,10:00,14:00,18:00,22:00'];
                            break;
                        default:
                            $ret = [];
                            break;
                    }
                }else{
                    $ret = [3,'06:00,14:00,18:00'];
                }
                break;
            case 4:  //  病危患者
                $ret = [6,'02:00,06:00,10:00,14:00,18:00,22:00'];
                break;
            case 5:  //病重患者
                if($temperature >= 38.5){
                    $ret = [6,'02:00,06:00,10:00,14:00,18:00,22:00'];
                }elseif($temperature >= 37.5) {
                    $ret = [4,'06:00,14:00,18:00,22:00'];
                }else{
                    $ret = [3,'06:00,14:00,18:00'];
                }
                break;
            case 6:  //入院时间在22:00之后的患者
                if($is_fara == 1){
                    switch($fare_level){
                        case 1:
                            $ret = [3,'06:00,14:00,18:00'];
                            break;
                        case 2:
                            $ret = [4,'06:00,14:00,18:00,22:00'];
                            break;
                        case 3:
                            $ret = [6,'02:00,06:00,10:00,14:00,18:00,22:00'];
                            break;
                        default:
                            $ret = [];
                            break;
                    }
                }else{
                    $ret = [2,'06:00,14:00'];
                }
                break;
        }
        return $ret;
    }
}
